package com.wenqian.server.http;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

// HTTP请求的解析与封装 ：别人发给我们的原材料
public class HttpRequest {
    private String method;
    private String path;
    private String version;
    private Map<String, String> headers = new HashMap<>();
    private String body;

    private HttpRequest(){}

    public static HttpRequest parse(InputStream in) throws IOException{
        HttpRequest request = new HttpRequest();
        // BufferedReader 内部有维护了一个缓存，比直接解析方便，
        // InputStreamReader将字节流转换成字符流，就是更方便BufferedReader
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        // 1. 解析请求行：GET /path HTTP/1.1
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()){
            throw new IOException("无效的HTTP请求行");
        }
        // requestLine.split(" ")是解析 HTTP 请求行的标准方式之一
        String[] parts = requestLine.split(" ");
        request.method = parts[0];
        request.path = parts[1];
        request.version = parts[2];

        // 2. 解析请求头
        String headerLine;
        while ((headerLine = reader.readLine()) != null && !headerLine.isEmpty()){
            String[] headerParts = headerLine.split(": ", 2); // Content-Type: text/html
            if (headerParts.length == 2) {
                request.headers.put(headerParts[0], headerParts[1]);
            }
        }

        // 3. 解析请求体 （主要针对Post）
        if ("POST".equalsIgnoreCase(request.method)) {
            int contentLength = Integer.parseInt(request.headers.getOrDefault("Content-Length", "0"));
            if (contentLength > 0) {
                char[] bodyChars = new char[contentLength];
                reader.read(bodyChars, 0, contentLength);
                request.body = new String(bodyChars);
            }
        }

        return request;
    }

    // Getters for all fields
    public String getMethod() { return method; }
    public String getPath() { return path; }
    public String getVersion() { return version; }
    public Map<String, String> getHeaders() { return headers; }
    public String getBody() { return body; }
}
